<script>
import {
  cloneDeep,
  getShowImage,
  showModal,
  showToast,
  valIsEmpty,
} from "../../../../../utils";
import nextIcon from "../../assets/next.png";
import prevIcon from "../../assets/previous.png";
import playIcon from "../../assets/play.png";
import successIcon from "../../assets/success.png";
import pauseIcon from "../../assets/pause.png";
import answerSheet from "./answerSheet.vue";
import moreMenu from "./moreMenu.vue";
import AnalysisVideo from "../analysisVideo.vue";
import paperIcon from "../../assets/paper.png";
import audioProcessBar from "./audioProcessBar.vue";
import popupPicker from "../../../../../components/popupPicker/index.vue";
import persistence from "../../../../../store/persistence";
import numberUtils from "../../../../../utils/numberUtils";
import loadingIcon from "../../assets/loading.png";
export default {
  name: "hearing.vue",
  computed: {
    currentQuestion() {
      return this.hearingTopicList[this.currentQuestionIndex];
    },
  },
  components: {
    AnalysisVideo,
    answerSheet,
    moreMenu,
    audioProcessBar,
    popupPicker,
  },
  props: {
    details: {
      type: Object,
      default: () => {},
    },
    //是否显示解析
    viewAnalysis: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      nextIcon,
      prevIcon,
      playIcon,
      successIcon,
      pauseIcon,
      paperIcon,
      loadingIcon,
      currentQuestionIndex: 0, //当前题目的索引
      audio: {
        pause: true, //听力音频是否处于暂停状态
        loading: false, //听力音频是否是处于加载中状态
      },
      currentSpeedRate: persistence.hearingAudioPlaySpeedRate.get(), //当前音频倍速
      persistence,
      hearingTopicList: [], //听力题目列表
      lastBtn: "", //用于标识用户点击的上一个按钮，以提供相应的样式效果进行标识，增强用户体验
			isViewParse: false, //是否展开解析
    };
  },
  watch: {
    viewAnalysis: {
      handler(val) {
        //重置题目索引
        this.currentQuestionIndex = 0;
      },
    },
    //组件内外环境隔离
    details: {
      handler(val) {
        if (val.hearingTopicList)
          this.hearingTopicList = cloneDeep(val.hearingTopicList);
      },
      immediate: true,
    },
  },
  methods: {
    //下一题
    nextQuestion() {
      //判断是否是最后一题
      if (this.currentQuestionIndex === this.hearingTopicList.length - 1) {
        showToast.default("已经是最后一题了");
        return;
      }
      //将页面滚动到最顶端
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
      this.currentQuestionIndex++;
      //更新音频进度
      this.$refs.audioProcessBar.switchSlice(this.currentQuestionIndex);
    },
    //上一题
    prevQuestion() {
      //判断是否是第一题
      if (this.currentQuestionIndex === 0) {
        showToast.default("已经是第一题了");
        return;
      }
      //将页面滚动到最顶端
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
      this.currentQuestionIndex--;
      //更新音频进度
      this.$refs.audioProcessBar.switchSlice(this.currentQuestionIndex);
    },
    //选择了选项
    optionSelected(questionItem, optionItem) {
      this.$set(questionItem, "userAnswer", optionItem.tag);
      questionItem.doRight = optionItem.answer;
    },
    //完成作答
    async finishAnswer() {
      let questionList = [];
      let unAnswer = false;
      //计算总题数，答对题数，答错题数，未答题数，本次答题得分
      const userDoTopicScore = {
        totalTopicNum: 0,
        rightTopicNum: 0,
        errorTopicNum: 0,
        noDoNum: 0,
        score: 0,
        isCalculateScore: 1, //评分
      };
      for (let item of this.hearingTopicList) {
        for (let item2 of item.questions) {
          //检查用户是否有作答
          if (!item2.userAnswer) {
            unAnswer = true;
          }
          //做对了
          if (item2.doRight) {
            userDoTopicScore.rightTopicNum++;
            //计算分数
            userDoTopicScore.score = numberUtils.preciseAdd(
              userDoTopicScore.score,
              item2.questionScore,
            );
          } else {
            //没有做
            if (valIsEmpty(item2.userAnswer)) {
              userDoTopicScore.noDoNum++;
              //做错了
            } else {
              userDoTopicScore.errorTopicNum++;
            }
          }
          //处理提交数据
          questionList.push({
            questionId: item2.childQuestionId,
            questionScore: item2.questionScore,
            questionSerialNum: item2.serialNum,
            userAnswer: item2.userAnswer,
            doRight: item2.doRight,
          });
        }
      }
			userDoTopicScore.totalTopicNum = questionList.length;
      if (
        unAnswer &&
        !(await showModal({
          title: "提示",
          content: "您还有题目未作答，是否继续提交？",
          confirmText: "确认提交",
          cancelText: "继续作答",
        }))
      ) {
        return;
      }
      this.$emit("submit", { questionList, userDoTopicScore });
    },
  },
  emits: ["submit", "handleCorrectQuestion"],
  inject: ["root"],
};
</script>

<template>
  <view class="component">
    <!--		答题区域-->
    <view class="content">
      <!--			题目名称-->
      <view class="title">
        <view class="point"></view>
        <view class="text">
          {{ currentQuestion.section }}
          &nbsp;
          {{ currentQuestion.questionName }}
        </view>
      </view>
      <slot></slot>
      <!--			解析内容-->
      <view
        v-if="currentQuestion.analysis && viewAnalysis"
        style="padding: 0 20rpx; margin-top: 60rpx"
      >
        <view v-html="currentQuestion.analysis"></view>
      </view>
      <!--			题目内容-->
      <view
        class="question-item"
        v-for="item in currentQuestion.questions"
        :key="item.serialNum"
      >
        <!--				小题题目名称-->
        <view class="question-serialNum">
          <view class="underline"></view>
          <view class="text">Question&nbsp;{{ item.serialNum }}</view>
        </view>
        <!--				小题选项列表-->
        <block v-for="option in item.childQuestions" :key="option.tag">
          <view class="option-item-text">
            <!--					做题模式，或者查看解析用户没有选择该选项以及该选项不为正确答案时展示时展示-->
            <view v-if="!viewAnalysis || (!option.userAnswer && !option.answer)"
              >【{{ option.tag }}】&nbsp;
            </view>
            <!--						查看答案解析，显示该题做对了还是做错了-->
            <view
              v-else
              class="option-tag"
              :class="option.answer ? 'success' : 'error'"
              >{{ option.tag }}
            </view>
            <view>
              <!--							选项内容-->
              <view>{{ option.content }}</view>
              <!--							选项翻译-->
              <view class="translate" v-if="viewAnalysis && option.trans">{{
                option.trans
              }}</view>
            </view>
          </view>
        </block>
        <!--				查看答案解析，标记该题是否有作答-->
        <view
          v-if="viewAnalysis && item.noDo"
          style="margin-top: 30rpx; color: darkred"
          >【未作答】
        </view>
        <!--				选项按钮列表-->
        <view class="option-btn-list" v-if="!viewAnalysis">
          <view
            class="option-btn-item"
            v-for="option in item.childQuestions"
            :key="option.tag"
            @click="optionSelected(item, option)"
            :class="[option.tag === item.userAnswer ? 'answer' : '']"
          >
            {{ option.tag }}
          </view>
        </view>
        <!--				题目解析-->
        <view
          class="question-analysis"
          v-if="viewAnalysis && (item.analysis || item.videoUrl)"
        >
          <view class="btn-container" v-if="!isViewParse">
            <view
              class="btn"
              @click="root.checkIsVip() && (isViewParse = true)"
              >查看解析
            </view>
          </view>
          <view class="content" v-else>
            <view v-html="item.analysis" class="item"></view>
            <view class="item">
              <analysis-video
                :video-file-url="item.videoUrl"
                v-if="item.videoUrl"
              ></analysis-video>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!--		底部控制栏-->
    <view class="placeholder"></view>
    <view class="footer">
      <!--			音频进度条-->
      <audio-process-bar
        ref="audioProcessBar"
        :view-analysis="viewAnalysis"
        :hearing-topic-list="details.hearingTopicList"
        :pause.sync="audio.pause"
        :loading.sync="audio.loading"
        :audioSrc="details.hearingFileUrl"
        :play-speed-rate="currentSpeedRate"
				@handleSpeedRateModify="$refs.speedRatePicker.open()"
        @update:currentQuestionIndex="
          (index) => {
            currentQuestionIndex = index;
          }
        "
      ></audio-process-bar>
      <view class="footer-btn-list">
        <!--				更多-->
        <view class="btn-item">
          <moreMenu
            :details="details"
            @handleSpeedRateModify="$refs.speedRatePicker.open()"
          ></moreMenu>
        </view>
        <!--			答题卡-->
        <view
          class="btn-item"
          @click="$refs.answerSheet.open(hearingTopicList)"
        >
          <image class="icon" :src="paperIcon"></image>
          <view class="text">答题卡</view>
        </view>
        <!--				上一题按钮-->
        <view
          class="btn-item"
          @click="
            lastBtn = 'prevQuestion';
            prevQuestion();
          "
          :class="[lastBtn === 'prevQuestion' ? 'active' : '']"
        >
          <image class="icon" :src="prevIcon"></image>
          <view class="text">上一题</view>
        </view>
        <!--				音频加载中按钮-->
        <view
          class="btn-item"
          v-if="audio.loading"
          @click="$refs.audioProcessBar.handlePause()"
        >
          <image class="icon" :src="loadingIcon"></image>
          <view class="text">缓冲中</view>
        </view>
        <!--				暂停 / 播放按钮-->
        <view
          class="btn-item"
          v-else-if="audio.pause"
          @click="$refs.audioProcessBar.play()"
        >
          <image class="icon" :src="playIcon"></image>
          <view class="text">播放</view>
        </view>
        <view
          class="btn-item"
          v-else
          @click="$refs.audioProcessBar.handlePause()"
        >
          <image class="icon" :src="pauseIcon" mode="heightFix"></image>
          <view class="text">暂停</view>
        </view>
        <!--				下一题按钮-->
        <view
          class="btn-item"
          @click="
            lastBtn = 'nextQuestion';
            nextQuestion();
          "
          :class="[lastBtn === 'nextQuestion' ? 'active' : '']"
        >
          <image class="icon" :src="nextIcon"></image>
          <view class="text">下一题</view>
        </view>
        <!--				完成作答-->
        <view class="btn-item" @click="finishAnswer" v-if="!viewAnalysis">
          <image class="icon" :src="successIcon" mode="heightFix"></image>
          <view class="text">提交</view>
        </view>
      </view>
    </view>
    <!--		答题卡-->
    <answer-sheet
      ref="answerSheet"
      :view-analysis="viewAnalysis"
      @select="
        (index) => {
          currentQuestionIndex = index;
          //更新音频进度
          $refs.audioProcessBar.switchSlice(index);
        }
      "
    ></answer-sheet>
    <!--		倍速调节-->
    <popupPicker
      ref="speedRatePicker"
      :picker-option-list="[
        { value: 0.5, label: '0.5' },
        { value: 0.75, label: '0.75' },
        { value: 1, label: '1' },
        { value: 1.25, label: '1.25' },
        { value: 1.5, label: '1.5' },
        { value: 2, label: '2' },
      ]"
      v-model="currentSpeedRate"
      @change="
        (item) => {
          persistence.hearingAudioPlaySpeedRate.set(item.value);
        }
      "
    ></popupPicker>
  </view>
</template>

<style scoped lang="scss">
.component {
  > .content {
    > .title {
      display: flex;
      padding: {
        top: 20rpx;
        left: 20rpx;
        right: 20rpx;
      }
      align-items: center;
      > .point {
        width: 20rpx;
        height: 40rpx;
        background: var(--theme-color);
        margin-right: 20rpx;
      }
      > .text {
        font-size: calc(34rpx * var(--font-size-rate));
      }
    }
    > .question-item {
      margin-top: 60rpx;
      padding: 0 20rpx;
      .question-serialNum {
        position: relative;
        height: 44rpx;
        width: 180rpx;
        > .underline {
          position: absolute;
          bottom: 0;
          left: 0;
          height: 20rpx;
          background: var(--theme-color);
          width: 100%;
          border-radius: 10%;
        }
        > .text {
          font-size: calc(34rpx * var(--font-size-rate));
          font-weight: bold;
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          z-index: 11;
        }
      }
      .option-item-text {
        margin-top: 50rpx;
        font-size: calc(34rpx * var(--font-size-rate));
        display: flex;
        align-items: center;
        .translate {
          color: var(--text-color-light);
          font-size: calc(30rpx * var(--font-size-rate));
        }

        .option-tag {
          padding: 10rpx 20rpx;
          border-radius: 32rpx;
          margin-right: 20rpx;
          margin-left: 10rpx;
          color: white;
          &.success {
            background: #1b9b69;
          }
          &.error {
            background: #e94f4f;
          }
        }
      }
      .option-btn-list {
        margin-top: 50rpx;
        display: flex;
        .option-btn-item {
          width: 0;
          flex: 1;
          height: 70rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: var(--gray-background-color);
          border-radius: 35rpx;
          &:not(:last-child) {
            margin-right: 20rpx;
          }
          &.answer {
            background: var(--subtheme-color);
          }
        }
      }
      .question-analysis {
        margin-top: 30rpx;
        > .btn-container {
          display: flex;
          justify-content: flex-end;
          > .btn {
            display: flex;
            align-items: center;
            height: 60rpx;
            padding: 0 30rpx;
            background: var(--theme-color);
            font-size: calc(30rpx * var(--font-size-rate));
            border-radius: 30rpx;
						color: var(--text-color-white);
          }
        }
        > .content {
          background: var(--gray-background-color);
          padding: 30rpx;
          border-radius: 20rpx;
          margin-top: 30rpx;
          .item:not(:first-child) {
            margin-top: 20rpx;
          }
        }
      }
    }
  }
  > .placeholder {
    height: calc(312rpx + env(safe-area-inset-bottom));
  }
  > .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding-bottom: env(safe-area-inset-bottom);
    border-top: 2rpx solid var(--border-color);
    background: white;
    z-index: 89;
    .footer-btn-list {
      display: flex;
      padding-bottom: calc(30rpx * var(--font-size-rate));
      .btn-item {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        width: 0;
        flex: 1;
        &:not(:last-child) {
          margin-right: calc(20rpx * var(--font-size-rate));
        }
        &.active {
          color: var(--text-color-theme);
        }
        > .icon {
          height: calc(50rpx * var(--font-size-rate));
          max-width: calc(50rpx * var(--font-size-rate));
        }
        > .text {
          margin-top: calc(10rpx * var(--font-size-rate));
          font-size: calc(28rpx * var(--font-size-rate));
        }
      }
    }
  }
}
</style>
